//
//  ColorPicker.swift
//  ColorPickerLib
//
//  Created by youmy on 2021/2/23.
//

import UIKit

public protocol ColorPickerProtocol {
    func didSelectColor(_ color: UIColor)
}

public class ColorPicker: UIView {

    public typealias SelectColor = (_ color: UIColor?) -> Void

    public var selectColor: SelectColor?
    public var delegate: ColorPickerProtocol?

    let bundle = "Frameworks/ColorPickerLib.framework/Resource.bundle/"
    var paletteImageV: UIImageView?
    var indicatorImageV: UIImageView?

    public override init(frame: CGRect) {
        super.init(frame: frame)
        buildColorPicker()
    }

    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func buildColorPicker() {
        print("path: \(bundle)")
        let image = UIImage(named: bundle + "paletteColor")?.reSizeImage(reSize: bounds.size)
        paletteImageV = UIImageView(frame: bounds)
        paletteImageV?.image = image
        addSubview(paletteImageV!)

        indicatorImageV = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        indicatorImageV?.image = UIImage(named: bundle + "xishe")
        indicatorImageV?.center = paletteImageV?.center ?? .zero
        addSubview(indicatorImageV!)
    }

    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let point = touch.location(in: self)

            let chassRadius = bounds.width/2 - 20
            let absDistanceX = abs(point.x - bounds.width/2)
            let absDistanceY = abs(point.y - bounds.height/2)
            let currentTopointRadius = sqrt(Double(absDistanceX * absDistanceX + absDistanceY * absDistanceY))

            if CGFloat(currentTopointRadius) < chassRadius, let color = getPointColor(point: point) {
                indicatorImageV?.center = point
                delegate?.didSelectColor(color)
                selectColor?(color)
            }
        }
    }

    open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let point = touch.location(in: self)

            let chassRadius = bounds.width/2
            let absDistanceX = abs(point.x - bounds.width/2)
            let absDistanceY = abs(point.y - bounds.height/2)
            let currentTopointRadius = sqrt(Double(absDistanceX * absDistanceX + absDistanceY * absDistanceY))

            if CGFloat(currentTopointRadius) < chassRadius, let color = getPointColor(point: point) {
                indicatorImageV?.center = point
                delegate?.didSelectColor(color)
                selectColor?(color)
            }
        }
    }

    func getPointColor(point: CGPoint) -> UIColor? {

        guard let image = paletteImageV?.image, CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size).contains(point) else {
            return nil
        }

        let pointX = trunc(point.x);
        let pointY = trunc(point.y);

        let width = image.size.width;
        let height = image.size.height;
        let colorSpace = CGColorSpaceCreateDeviceRGB();
        var pixelData: [UInt8] = [0, 0, 0, 0]

        pixelData.withUnsafeMutableBytes { pointer in
            if let context = CGContext(data: pointer.baseAddress, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue), let cgImage = image.cgImage {
                context.setBlendMode(.copy)
                context.translateBy(x: -pointX, y: pointY - height)
                context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
            }
        }

        let red = CGFloat(pixelData[0]) / CGFloat(255.0)
        let green = CGFloat(pixelData[1]) / CGFloat(255.0)
        let blue = CGFloat(pixelData[2]) / CGFloat(255.0)
        let alpha = CGFloat(pixelData[3]) / CGFloat(255.0)

        if #available(iOS 10.0, *) {
            return UIColor(displayP3Red: red, green: green, blue: blue, alpha: alpha)
        } else {
            return UIColor(red: red, green: green, blue: blue, alpha: alpha)
        }
    }
}

extension UIImage {
    /**
     *  重设图片大小
     */
    func reSizeImage(reSize:CGSize) -> UIImage? {
        //UIGraphicsBeginImageContext(reSize)
        UIGraphicsBeginImageContextWithOptions(reSize,false,UIScreen.main.scale)
        draw(in: CGRect(x: 0, y: 0, width: reSize.width, height: reSize.height))
        let reSizeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return reSizeImage
    }

    /**
     *  等比率缩放
     */
    func scaleImage(scaleSize: CGFloat) -> UIImage? {
        let reSize = CGSize(width: size.width * scaleSize, height: size.height * scaleSize)
        return reSizeImage(reSize: reSize)
    }
}
